<template>
  <div class="marketing-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <h2>营销管理</h2>
      </div>
    </div>

    <!-- 数据概览 -->
    <a-row :gutter="16" class="data-overview">
      <a-col :span="6" v-for="card in overviewCards" :key="card.title">
        <a-card class="overview-card" :bordered="false">
          <div class="card-content">
            <div class="card-title">{{ card.title }}</div>
            <div class="card-value">{{ card.value }}</div>
            <div class="card-chart">
              <!-- 这里可以集成迷你图表 -->
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 营销工具 -->
    <div class="marketing-tools">
      <a-row :gutter="16">
        <!-- 优惠券管理 -->
        <a-col :span="12">
          <a-card class="tool-card" title="优惠券管理" :bordered="false">
            <template #extra>
              <a-button type="primary" @click="handleCreateCoupon">
                <template #icon><icon-plus /></template>
                新建优惠券
              </a-button>
            </template>

            <!-- 优惠券列表 -->
            <a-table
              :columns="couponColumns"
              :data="couponList"
              :pagination="false"
              :bordered="false"
            >
              <!-- 优惠券信息 -->
              <template #info="{ record }">
                <div class="coupon-info">
                  <div class="coupon-name">{{ record.name }}</div>
                  <div class="coupon-type">{{ record.typeText }}</div>
                </div>
              </template>

              <!-- 优惠内容 -->
              <template #discount="{ record }">
                <div class="discount-info">
                  <span v-if="record.type === 'amount'" class="amount">
                    ¥{{ record.value }}
                  </span>
                  <span v-else-if="record.type === 'discount'" class="discount">
                    {{ record.value }}折
                  </span>
                  <div class="condition">满{{ record.minAmount }}元可用</div>
                </div>
              </template>

              <!-- 有效期 -->
              <template #validity="{ record }">
                <div class="validity-info">
                  <div>{{ record.startTime }}</div>
                  <div>至</div>
                  <div>{{ record.endTime }}</div>
                </div>
              </template>

              <!-- 发放情况 -->
              <template #distribution="{ record }">
                <div class="distribution-info">
                  <div>已发放：{{ record.issuedCount }}</div>
                  <div>已使用：{{ record.usedCount }}</div>
                  <div>剩余：{{ record.remainingCount }}</div>
                </div>
              </template>

              <!-- 状态 -->
              <template #status="{ record }">
                <a-tag :color="getCouponStatusColor(record.status)">
                  {{ record.statusText }}
                </a-tag>
              </template>

              <!-- 操作 -->
              <template #operations="{ record }">
                <a-space>
                  <a-button
                    type="text"
                    size="small"
                    @click="handleEditCoupon(record)"
                  >
                    编辑
                  </a-button>
                  <a-button
                    type="text"
                    size="small"
                    status="danger"
                    @click="handleDeleteCoupon(record)"
                  >
                    删除
                  </a-button>
                </a-space>
              </template>
            </a-table>
          </a-card>
        </a-col>

        <!-- 促销活动 -->
        <a-col :span="12">
          <a-card class="tool-card" title="促销活动" :bordered="false">
            <template #extra>
              <a-button type="primary" @click="handleCreatePromotion">
                <template #icon><icon-plus /></template>
                新建活动
              </a-button>
            </template>

            <!-- 活动列表 -->
            <a-table
              :columns="promotionColumns"
              :data="promotionList"
              :pagination="false"
              :bordered="false"
            >
              <!-- 活动信息 -->
              <template #info="{ record }">
                <div class="promotion-info">
                  <div class="promotion-name">{{ record.name }}</div>
                  <div class="promotion-type">{{ record.typeText }}</div>
                </div>
              </template>

              <!-- 活动规则 -->
              <template #rules="{ record }">
                <div class="rules-info">
                  <div v-for="(rule, index) in record.rules" :key="index">
                    {{ rule }}
                  </div>
                </div>
              </template>

              <!-- 有效期 -->
              <template #validity="{ record }">
                <div class="validity-info">
                  <div>{{ record.startTime }}</div>
                  <div>至</div>
                  <div>{{ record.endTime }}</div>
                </div>
              </template>

              <!-- 参与情况 -->
              <template #participation="{ record }">
                <div class="participation-info">
                  <div>参与人数：{{ record.participantCount }}</div>
                  <div>订单数：{{ record.orderCount }}</div>
                  <div>销售额：¥{{ record.salesAmount }}</div>
                </div>
              </template>

              <!-- 状态 -->
              <template #status="{ record }">
                <a-tag :color="getPromotionStatusColor(record.status)">
                  {{ record.statusText }}
                </a-tag>
              </template>

              <!-- 操作 -->
              <template #operations="{ record }">
                <a-space>
                  <a-button
                    type="text"
                    size="small"
                    @click="handleEditPromotion(record)"
                  >
                    编辑
                  </a-button>
                  <a-button
                    type="text"
                    size="small"
                    status="danger"
                    @click="handleDeletePromotion(record)"
                  >
                    删除
                  </a-button>
                </a-space>
              </template>
            </a-table>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 优惠券弹窗 -->
    <a-modal
      v-model:visible="couponVisible"
      :title="couponForm.id ? '编辑优惠券' : '新建优惠券'"
      @ok="handleCouponSubmit"
      @cancel="handleCouponCancel"
    >
      <a-form :model="couponForm" layout="vertical">
        <a-form-item field="name" label="优惠券名称">
          <a-input
            v-model="couponForm.name"
            placeholder="请输入优惠券名称"
            allow-clear
          />
        </a-form-item>

        <a-form-item field="type" label="优惠类型">
          <a-radio-group v-model="couponForm.type">
            <a-radio value="amount">满减券</a-radio>
            <a-radio value="discount">折扣券</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item field="value" label="优惠金额/折扣">
          <a-input-number
            v-model="couponForm.value"
            :min="0"
            :max="couponForm.type === 'amount' ? 99999 : 10"
            :precision="couponForm.type === 'amount' ? 2 : 1"
            :prefix="couponForm.type === 'amount' ? '¥' : ''"
            :suffix="couponForm.type === 'discount' ? '折' : ''"
            :style="{ width: '100%' }"
          />
        </a-form-item>

        <a-form-item field="minAmount" label="使用门槛">
          <a-input-number
            v-model="couponForm.minAmount"
            :min="0"
            :precision="2"
            prefix="¥"
            placeholder="请输入最低消费金额"
            :style="{ width: '100%' }"
          />
        </a-form-item>

        <a-form-item field="validity" label="有效期">
          <a-range-picker
            v-model="couponForm.validity"
            show-time
            style="width: 100%"
          />
        </a-form-item>

        <a-form-item field="totalCount" label="发放数量">
          <a-input-number
            v-model="couponForm.totalCount"
            :min="1"
            :precision="0"
            placeholder="请输入发放数量"
            :style="{ width: '100%' }"
          />
        </a-form-item>

        <a-form-item field="description" label="使用说明">
          <a-textarea
            v-model="couponForm.description"
            placeholder="请输入使用说明"
            :max-length="200"
            show-word-limit
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 活动弹窗 -->
    <a-modal
      v-model:visible="promotionVisible"
      :title="promotionForm.id ? '编辑活动' : '新建活动'"
      @ok="handlePromotionSubmit"
      @cancel="handlePromotionCancel"
    >
      <a-form :model="promotionForm" layout="vertical">
        <a-form-item field="name" label="活动名称">
          <a-input
            v-model="promotionForm.name"
            placeholder="请输入活动名称"
            allow-clear
          />
        </a-form-item>

        <a-form-item field="type" label="活动类型">
          <a-radio-group v-model="promotionForm.type">
            <a-radio value="discount">折扣活动</a-radio>
            <a-radio value="fullReduction">满减活动</a-radio>
            <a-radio value="groupBuy">团购活动</a-radio>
            <a-radio value="secondHalf">第二件半价</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item field="products" label="参与商品">
          <a-select
            v-model="promotionForm.products"
            placeholder="请选择参与商品"
            multiple
            allow-clear
          >
            <a-option
              v-for="product in productOptions"
              :key="product.value"
              :value="product.value"
              :label="product.label"
            />
          </a-select>
        </a-form-item>

        <a-form-item field="rules" label="活动规则">
          <div v-if="promotionForm.type === 'discount'">
            <a-input-number
              v-model="promotionForm.discount"
              :min="0"
              :max="10"
              :precision="1"
              suffix="折"
              :style="{ width: '100%' }"
            />
          </div>

          <div v-if="promotionForm.type === 'fullReduction'">
            <a-space direction="vertical" :style="{ width: '100%' }">
              <div
                v-for="(rule, index) in promotionForm.rules"
                :key="index"
                class="rule-item"
              >
                满
                <a-input-number
                  v-model="rule.full"
                  :min="0"
                  :precision="2"
                  style="width: 120px"
                />
                减
                <a-input-number
                  v-model="rule.reduction"
                  :min="0"
                  :precision="2"
                  style="width: 120px"
                />
                <a-button
                  type="text"
                  status="danger"
                  @click="handleRemoveRule(index)"
                >
                  删除
                </a-button>
              </div>
              <a-button type="dashed" @click="handleAddRule">
                添加规则
              </a-button>
            </a-space>
          </div>
        </a-form-item>

        <a-form-item field="validity" label="活动时间">
          <a-range-picker
            v-model="promotionForm.validity"
            show-time
            style="width: 100%"
          />
        </a-form-item>

        <a-form-item field="description" label="活动说明">
          <a-textarea
            v-model="promotionForm.description"
            placeholder="请输入活动说明"
            :max-length="200"
            show-word-limit
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { Message } from "@arco-design/web-vue";
import { IconPlus } from "@arco-design/web-vue/es/icon";

// 数据概览
const overviewCards = [
  {
    title: "优惠券核销率",
    value: "68.5%",
  },
  {
    title: "活动参与人数",
    value: "1,234",
  },
  {
    title: "活动订单数",
    value: "856",
  },
  {
    title: "活动销售额",
    value: "¥123,456",
  },
];

// 优惠券列表配置
const couponColumns = [
  {
    title: "优惠券信息",
    dataIndex: "info",
    slotName: "info",
  },
  {
    title: "优惠内容",
    dataIndex: "discount",
    slotName: "discount",
  },
  {
    title: "有效期",
    dataIndex: "validity",
    slotName: "validity",
  },
  {
    title: "发放情况",
    dataIndex: "distribution",
    slotName: "distribution",
  },
  {
    title: "状态",
    dataIndex: "status",
    slotName: "status",
  },
  {
    title: "操作",
    slotName: "operations",
    width: 120,
  },
];

// 优惠券列表数据
const couponList = ref([
  {
    id: 1,
    name: "新人专享券",
    type: "amount",
    typeText: "满减券",
    value: 10,
    minAmount: 100,
    startTime: "2024-03-15",
    endTime: "2024-04-15",
    issuedCount: 1000,
    usedCount: 500,
    remainingCount: 500,
    status: "active",
    statusText: "进行中",
  },
  // ... 更多优惠券数据
]);

// 促销活动列表配置
const promotionColumns = [
  {
    title: "活动信息",
    dataIndex: "info",
    slotName: "info",
  },
  {
    title: "活动规则",
    dataIndex: "rules",
    slotName: "rules",
  },
  {
    title: "有效期",
    dataIndex: "validity",
    slotName: "validity",
  },
  {
    title: "参与情况",
    dataIndex: "participation",
    slotName: "participation",
  },
  {
    title: "状态",
    dataIndex: "status",
    slotName: "status",
  },
  {
    title: "操作",
    slotName: "operations",
    width: 120,
  },
];

// 促销活动列表数据
const promotionList = ref([
  {
    id: 1,
    name: "春季特惠",
    type: "discount",
    typeText: "折扣活动",
    rules: ["全场8折"],
    startTime: "2024-03-15",
    endTime: "2024-04-15",
    participantCount: 500,
    orderCount: 300,
    salesAmount: "29,999",
    status: "active",
    statusText: "进行中",
  },
  // ... 更多活动数据
]);

// 商品选项
const productOptions = [
  { label: "商品1", value: 1 },
  { label: "商品2", value: 2 },
  // ... 更多商品选项
];

// 优惠券弹窗
const couponVisible = ref(false);
const couponForm = reactive({
  id: null,
  name: "",
  type: "amount",
  value: null,
  minAmount: null,
  validity: [],
  totalCount: null,
  description: "",
});

// 活动弹窗
const promotionVisible = ref(false);
const promotionForm = reactive({
  id: null,
  name: "",
  type: "discount",
  products: [],
  discount: null,
  rules: [],
  validity: [],
  description: "",
});

// 获取优惠券状态颜色
const getCouponStatusColor = (status) => {
  const colorMap = {
    active: "green",
    expired: "red",
    depleted: "gray",
  };
  return colorMap[status] || "blue";
};

// 获取活动状态颜色
const getPromotionStatusColor = (status) => {
  const colorMap = {
    active: "green",
    ended: "red",
    upcoming: "blue",
  };
  return colorMap[status] || "gray";
};

// 创建优惠券
const handleCreateCoupon = () => {
  couponForm.id = null;
  couponForm.name = "";
  couponForm.type = "amount";
  couponForm.value = null;
  couponForm.minAmount = null;
  couponForm.validity = [];
  couponForm.totalCount = null;
  couponForm.description = "";
  couponVisible.value = true;
};

// 编辑优惠券
const handleEditCoupon = (record) => {
  Object.assign(couponForm, record);
  couponVisible.value = true;
};

// 删除优惠券
const handleDeleteCoupon = (record) => {
  Message.success("删除成功");
};

// 提交优惠券
const handleCouponSubmit = async () => {
  try {
    // TODO: 调用保存API
    await new Promise((resolve) => setTimeout(resolve, 1000));
    Message.success("保存成功");
    couponVisible.value = false;
  } catch (error) {
    Message.error("保存失败");
  }
};

// 取消优惠券
const handleCouponCancel = () => {
  couponVisible.value = false;
};

// 创建活动
const handleCreatePromotion = () => {
  promotionForm.id = null;
  promotionForm.name = "";
  promotionForm.type = "discount";
  promotionForm.products = [];
  promotionForm.discount = null;
  promotionForm.rules = [];
  promotionForm.validity = [];
  promotionForm.description = "";
  promotionVisible.value = true;
};

// 编辑活动
const handleEditPromotion = (record) => {
  Object.assign(promotionForm, record);
  promotionVisible.value = true;
};

// 删除活动
const handleDeletePromotion = (record) => {
  Message.success("删除成功");
};

// 添加满减规则
const handleAddRule = () => {
  promotionForm.rules.push({
    full: null,
    reduction: null,
  });
};

// 删除满减规则
const handleRemoveRule = (index) => {
  promotionForm.rules.splice(index, 1);
};

// 提交活动
const handlePromotionSubmit = async () => {
  try {
    // TODO: 调用保存API
    await new Promise((resolve) => setTimeout(resolve, 1000));
    Message.success("保存成功");
    promotionVisible.value = false;
  } catch (error) {
    Message.error("保存失败");
  }
};

// 取消活动
const handlePromotionCancel = () => {
  promotionVisible.value = false;
};
</script>

<style lang="scss" scoped>
.marketing-page {
  .page-header {
    @apply mb-6;

    h2 {
      @apply text-xl font-medium;
    }
  }

  .data-overview {
    @apply mb-6;

    .overview-card {
      @apply bg-white rounded-lg transition-shadow hover:shadow-md;

      .card-content {
        @apply space-y-2;

        .card-title {
          @apply text-sm text-gray-600;
        }

        .card-value {
          @apply text-2xl font-medium;
        }

        .card-chart {
          @apply h-10;
        }
      }
    }
  }

  .marketing-tools {
    .tool-card {
      @apply mb-6 bg-white rounded-lg;

      :deep(.arco-card-header) {
        @apply border-0 border-b;
      }
    }
  }

  .coupon-info {
    .coupon-name {
      @apply font-medium mb-1;
    }

    .coupon-type {
      @apply text-sm text-gray-500;
    }
  }

  .discount-info {
    .amount {
      @apply text-red-500 font-medium;
    }

    .discount {
      @apply text-orange-500 font-medium;
    }

    .condition {
      @apply text-sm text-gray-500 mt-1;
    }
  }

  .validity-info {
    @apply text-sm space-y-1;
  }

  .distribution-info {
    @apply text-sm space-y-1;
  }

  .promotion-info {
    .promotion-name {
      @apply font-medium mb-1;
    }

    .promotion-type {
      @apply text-sm text-gray-500;
    }
  }

  .rules-info {
    @apply text-sm space-y-1;
  }

  .participation-info {
    @apply text-sm space-y-1;
  }

  .rule-item {
    @apply flex items-center space-x-2;
  }
}
</style>
